import TableSelects from '@/component/common/tableSelects/tableSelects'
import { Button, Empty, Flex, Input, Popconfirm, Select, Tag } from 'antd'
import MyTable from '@/component/common/myTable'
import { useMessageApi } from '@/component/context/messageContext/message'
import { useEffect, useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import quesApi from './api'
import { MyDrawer } from '@/component/common/myDrawer'
import QuestionType from '@/component/common/questionType'
import quesTypeApi from '../quesType/api'
import tagApi from '../tag/api'

const columns: any = [
  {
    title: '预览',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    render: (text: any, record: any) => {
      return record.title
    },
  },
  {
    title: '类型',
    dataIndex: 'type_name',
    key: 'type_name',
    align: 'center',
  },
  {
    title: '标签',
    dataIndex: 'tagNames',
    key: 'tagNames',
    align: 'center',
    render: (text: any, record: any) => {
      return record.tagNames.map((item: any) => {
        return <Tag key={item}>{item}</Tag>
      })
    },
  },
]

function Question() {
  const navigate = useNavigate()
  const messageApi = useMessageApi()
  const location = useLocation()
  const [tagState, setTagState] = useState([])
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    title: '',
    type: '',
  })
  const [loading, setLoading] = useState<boolean>(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])
  const [questionState, setQuestionState] = useState({
    tableData: [],
    total: 0,
  })
  const [currentQuestion, setCurrentQuestion] = useState<any>({
    title: '',
    data: [],
    tagIds: [],
  })
  const [switchState, setSwitchState] = useState({
    isShowAdd: false,
    isShowEdit: false,
  })
  const [quesTypeState, setQuesTypeState] = useState([])

  // 过滤器组件
  const Filter = () => {
    const tableOptions = [
      {
        render: (
          <Input
            key="title"
            placeholder="请输入题目标题"
            value={searchParams.title}
            allowClear
            onChange={(e) => {
              setSearchParams((oldV) => {
                return { ...oldV, title: e.target.value }
              })
            }}
          />
        ),
      },
      {
        render: (
          <Input
            key="type"
            placeholder="请输入题目类型"
            value={searchParams.type}
            allowClear
            onChange={(e) => {
              setSearchParams((oldV) => {
                return { ...oldV, type: e.target.value }
              })
            }}
          />
        ),
      },
    ]
    return (
      <TableSelects
        loading={loading}
        options={tableOptions}
        source={searchParams}
        onSearch={() => {
          navigate({
            search: `?pageNum=${searchParams.pageNum}&pageSize=${searchParams.pageSize}&title=${searchParams.title}&type=${searchParams.type}`,
          })
        }}
        buttonChildren={
          <Flex gap={'10px'}>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除这 ${selectedRowKeys.length} 道题目吗？`}
                onConfirm={() => {
                  delQuestion(selectedRowKeys)
                }}>
                <Button>删除</Button>
              </Popconfirm>
            )}
            <Button
              onClick={() => {
                setCurrentQuestion({
                  title: '',
                  data: [],
                })
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: true }
                })
              }}>
              添加
            </Button>
          </Flex>
        }></TableSelects>
    )
  }

  // 获取题目列表
  const getQuestions = (params: any) => {
    setLoading(true)
    quesApi.getQues(params).then((data: any) => {
      setQuestionState((oldV) => {
        return {
          ...oldV,
          tableData: data.ques.map((item: any) => {
            return {
              ...item,
              data: JSON.parse(item.data),
              answer: JSON.parse(item.answer),
              tagNames: item.tagNames.split(','),
              tagIds: item.tagIds.split(','),
            }
          }),
          total: data.total,
        }
      })
      setTimeout(() => {
        setLoading(false)
      }, 300)
    })
  }

  // 获取标签api
  const getTags = () => {
    tagApi
      .getTags({
        pageNum: 1,
        pageSize: 999,
        name: '',
      })
      .then((res: any) => {
        const temp = res.tags.map((item: any) => {
          return {
            label: item.name,
            value: `${item.id}`,
            color: item.color,
          }
        })
        setTagState(temp)
      })
  }

  // 删除题目
  const delQuestion = (ids: Array<number>) => {
    quesApi.delQues(ids).then(() => {
      messageApi.success('删除成功')
      getQuestions(searchParams)
    })
  }

  // 监听URL参数变化
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search)
    const params = {
      pageNum: searchParams.get('pageNum')
        ? Number(searchParams.get('pageNum'))
        : 1,
      pageSize: searchParams.get('pageSize')
        ? Number(searchParams.get('pageSize'))
        : 20,
      title: searchParams.get('title') ? String(searchParams.get('title')) : '',
      type: searchParams.get('type') ? String(searchParams.get('type')) : '',
    }
    setSearchParams(params)
    getQuestions(params)
    getTags()
  }, [location.search])

  // 表格组件
  const Table = useMemo(() => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys)
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    }
    return (
      <MyTable
        loading={loading}
        rowSelection={rowSelection}
        rowKey={(record) => record.id}
        dataSource={questionState?.tableData}
        columns={columns}
        pageSize={searchParams.pageSize}
        total={questionState.total}
        onPaginationChange={(pageNum, pageSize) => {
          navigate({
            search: `?pageNum=${pageNum}&pageSize=${pageSize}&title=${searchParams.title}&type=${searchParams.type}`,
          })
        }}
        onRow={(record) => ({
          onClick: () => {
            setCurrentQuestion({ ...record })
            setSwitchState((oldV) => {
              return { ...oldV, isShowEdit: true }
            })
          },
        })}></MyTable>
    )
  }, [
    loading,
    navigate,
    questionState?.tableData,
    questionState.total,
    searchParams.title,
    searchParams.type,
    searchParams.pageSize,
  ])

  // 添加题目抽屉组件
  const AddQuestionDrawer = () => {
    return (
      <MyDrawer
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: false }
                })
              }}>
              返回
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                addQuestion(currentQuestion)
              }}>
              保存
            </Button>
          </Flex>
        }
        open={switchState.isShowAdd}
        width={'80%'}
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowAdd: false }
          })
        }>
        <Flex vertical gap={'1rem'}>
          <Flex vertical gap={'1rem'}>
            <div>选择题型：</div>
            <Select
              options={quesTypeState}
              style={{ width: '100%' }}
              onChange={(value, option) => {
                const data = (option as any).data
                data.forEach((item: any) => {
                  switch (item.type) {
                    case 'singleChoice':
                    case 'multipleChoice':
                      item.content = [
                        { label: 'A', value: 'A', content: '' },
                        { label: 'B', value: 'B', content: '' },
                        { label: 'C', value: 'C', content: '' },
                        { label: 'D', value: 'D', content: '' },
                      ]
                      break
                    case 'fillBlank':
                      item.content = [
                        { value: '' },
                        { value: '' },
                        { value: '' },
                      ]
                      break
                    default:
                      break
                  }
                })
                setCurrentQuestion((oldV: any) => {
                  return { type: value, type_name: (option as any).label, data }
                })
              }}></Select>
            <div>题目概述：</div>
            <Input
              placeholder="请输入题目概述"
              value={currentQuestion.title}
              onChange={(e) => {
                setCurrentQuestion((oldV: any) => {
                  return { ...oldV, title: e.target.value }
                })
              }}></Input>
            <div>题目标签：</div>
            <Select
              mode="multiple"
              allowClear
              options={tagState}
              onChange={(value) => {
                setCurrentQuestion((oldV: any) => {
                  return { ...oldV, tagIds: value }
                })
              }}></Select>
          </Flex>
          <Flex vertical gap={'1rem'}>
            <div>题目内容：</div>
            {currentQuestion.data?.length ? (
              <QuestionType
                state="WRITE"
                content={currentQuestion}
                onChange={(value) => {
                  setCurrentQuestion(value)
                }}></QuestionType>
            ) : (
              <Empty></Empty>
            )}
          </Flex>
        </Flex>
      </MyDrawer>
    )
  }

  // 编辑题目抽屉组件
  const EditQuestionDrawer = () => {
    return (
      <MyDrawer
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowEdit: false }
                })
              }}>
              返回
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                updateQuestion(currentQuestion)
              }}>
              保存
            </Button>
          </Flex>
        }
        open={switchState.isShowEdit}
        width={'80%'}
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowEdit: false }
          })
        }>
        <Flex vertical gap={'1rem'}>
          <div>题目概述：</div>
          <Input
            placeholder="请输入题目概述"
            value={currentQuestion.title}
            onChange={(e) => {
              setCurrentQuestion((oldV: any) => {
                return { ...oldV, title: e.target.value }
              })
            }}></Input>
          <div>题目标签：</div>
          <Select
            mode="multiple"
            defaultValue={currentQuestion.tagIds}
            allowClear
            options={tagState}
            onChange={(value) => {
              setCurrentQuestion((oldV: any) => {
                return { ...oldV, tagIds: value }
              })
            }}></Select>
          <div>题目内容：</div>
          <QuestionType
            state="WRITE"
            content={currentQuestion}
            onChange={(value) => {
              setCurrentQuestion(value)
            }}></QuestionType>
        </Flex>
      </MyDrawer>
    )
  }

  // 添加题目API调用
  const addQuestion = (params: any) => {
    quesApi.addQues(params).then(() => {
      messageApi.success('添加成功')
      setSwitchState((oldV) => {
        return { ...oldV, isShowAdd: false }
      })
      getQuestions(searchParams)
    })
  }

  // 更新题目API调用
  const updateQuestion = (params: any) => {
    quesApi.updateQues(params).then(() => {
      messageApi.success('更新成功')
      setSwitchState((oldV) => {
        return { ...oldV, isShowEdit: false }
      })
      getQuestions(searchParams)
    })
  }

  // 获取题型列表api
  const getQuesTypes = (params: any) => {
    setLoading(true)
    quesTypeApi.getQuesType(params).then((data: any) => {
      const options = data.quesTypes.map((item: any) => {
        return {
          label: item.name,
          value: item.id,
          data: JSON.parse(item.data),
        }
      })
      setQuesTypeState(options)
      setTimeout(() => {
        setLoading(false)
      }, 300)
    })
  }

  useEffect(() => {
    getQuesTypes({ name: '', pageNum: 1, pageSize: 999 })
  }, [])

  return (
    <>
      {AddQuestionDrawer()}
      {EditQuestionDrawer()}
      {Filter()}
      {Table}
    </>
  )
}

export default Question
